import styles from './index.module.scss';
import classNames from 'classnames';
import { useEffect, useRef } from 'react';

interface Props
  extends React.DetailedHTMLProps<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  className: string;
  maxLength: number;
  value?: string;
}

export default function Textarea({
  className,
  value = '',
  maxLength = 100,
  ...rest
}: Props) {
  const textRef = useRef<HTMLTextAreaElement>(null);
  useEffect(() => {
    // 光标定义到末尾
    textRef.current?.setSelectionRange(-1, -1);
  }, []);
  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        ref={textRef}
        className={classNames('textarea', className)}
        maxLength={maxLength}
        value={value}
        {...rest}
      />
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {value.length}/{maxLength}
      </div>
    </div>
  );
}
